package com.hyhy.hycloud.commons.util;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author lanpengfei
 * @date 2018-12-29
 */
public class BeanUtil {

    enum Ignore {
        /**
         * NULL值
         * 空值
         */
        NULL, EMPTY
    }

    public static String[] getIgnoreProperties(Object source, Ignore ignore) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        Set<String> emptyFields = new HashSet<>();
        switch (ignore) {
            case NULL:
                Arrays.stream(src.getPropertyDescriptors()).forEach(propertyDescriptor -> {
                    if (src.getPropertyValue(propertyDescriptor.getName()) == null) {
                        emptyFields.add(propertyDescriptor.getName());
                    }
                });
                break;
            case EMPTY:
                Arrays.stream(src.getPropertyDescriptors()).forEach(propertyDescriptor -> {
                    if (StringUtils.isEmpty(src.getPropertyValue(propertyDescriptor.getName()))) {
                        emptyFields.add(propertyDescriptor.getName());
                    }
                });
                break;
            default:
                break;
        }
        return emptyFields.toArray(new String[0]);
    }

    public static void copyPropertiesIgnoreNull(Object src, Object target) {
        BeanUtils.copyProperties(src, target, getIgnoreProperties(src, Ignore.NULL));
    }

    public static void copyPropertiesIgnoreEmpty(Object src, Object target) {
        BeanUtils.copyProperties(src, target, getIgnoreProperties(src, Ignore.EMPTY));
    }
}
